<template>
  <div class="stock-list">
    <div class="flex justify-between">
      <div>
        <el-form :inline="true">
          <el-form-item label="查验码：" label-width="80px">
            <el-input v-model="formOption.couponCode" placeholder="请输入查验码" />
          </el-form-item>
          <el-form-item label="兑换人信息：" label-width="110px">
            <ScrollSelect
              placeholder="请选择用户信息"
              :selected-value="formOption.userId"
              :get-list-methods="getListMethods"
              :get-list-format="getListFormat"
              :clearable="true"
              search-key="nickNameOrMobile"
              @selectedChange="selectedChange"
            />
          </el-form-item>

          <el-form-item label="兑换时间：" label-width="100px">
            <el-date-picker
              v-model="formOption.time"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd HH:mm:ss"
              format="yyyy-MM-dd HH:mm"
              style="width: 320px"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button class="ml-20" type="primary" @click="searchHandle">搜索</el-button>
          </el-form-item>
        </el-form>
      </div>

      <div>
        <el-button @click="exportFile()">导出当前页</el-button>
        <el-button @click="exportFile('all')">导出全部</el-button>
      </div>
    </div>

    <PageTable
      :options="options"
      :columns="columns"
      :data="dataSource"
      @selectChange="selectChange"
    />

    <Pagination
      v-show="total > 0"
      :total="total"
      :pageNo.sync="listQuery.pageNo"
      :pageSize.sync="listQuery.pageSize"
      @pagination="getDetailList"
    />
  </div>
</template>

<script>
import { export2Excel } from '@/utils/export'
export default {
  name: 'ExchangeList',
  data() {
    return {
      formOption: {
        couponCode: '',
        time: [],
        userId: ''
      },
      listQuery: {
        pageNo: 1,
        pageSize: 10
      },
      total: 0,
      columns: [
        {
          prop: 'couponCode',
          label: '兑换码',
          render: (h, { row }) => {
            return <div style={'color: #409eff'}>{row.couponCode}</div>
          }
        },
        {
          label: '兑换人信息',
          render: (h, { row }) => {
            return (
              <div>
                <div class={row.baseUserInfo.isNew ? 'flex' : ''}>
                  <span>{row.baseUserInfo.nickName}</span>
                  {row.baseUserInfo.isNew ? (
                    <el-tag class="ml-5" type="danger">
                      新用户
                    </el-tag>
                  ) : (
                    ''
                  )}
                </div>
                <div>{row.baseUserInfo.mobile}</div>
              </div>
            )
          }
        },
        {
          prop: 'count',
          label: '总张数',
          render: () => {
            return <div>x1</div>
          }
        },
        {
          prop: 'integral',
          label: '获得积分',
          render: (h, { row }) => {
            return <span>+{row.integral}</span>
          }
        },
        {
          prop: 'storeName',
          label: '销售渠道',
          render: (h, { row }) => {
            return <span>{row.storeName || '暂无'}</span>
          }
        },
        {
          prop: 'exchange_way',
          label: '兑换方式',
          render: () => {
            return <span>小程序扫码</span>
          }
        },
        {
          prop: 'createdTime',
          label: '生成时间'
        },
        {
          prop: 'usedTime',
          label: '兑换时间'
        }
      ],
      options: {
        border: true,
        select: true
      },
      ids: [],
      dataSource: [],
      selectList: [],
      getListMethods: params => {
        return this.getUserSelectList(params)
      },
      getListFormat: (list = []) => {
        // 下拉框数据格式
        return list.map(({ nickName, mobile, id }) => ({
          label: `${nickName} ${mobile}`,
          value: id
        }))
      }
    }
  },
  computed: {
    id() {
      return this.$route.query?.id
    }
  },
  watch: {
    selectList(list) {
      this.ids = list?.map(item => item.id)
    }
  },
  created() {
    this.getDetailList()
  },
  methods: {
    // 获取用户信息
    async getUserSelectList(params) {
      const {
        data: { records }
      } = await this.$http.user.user.getUserSelectList({ params })
      return records
    },
    // 监听选择用户信息
    selectedChange(id) {
      this.formOption.userId = id
    },
    // 获取详情列表
    async getDetailList() {
      const params = {
        // 0: 未出库, 1: 未兑换, 2: 已兑换, 3: 作废
        couponId: this.id,
        status: 2,
        ...this.listQuery
      }
      const { couponCode, time, userId } = this.formOption
      if (couponCode) params.couponCode = couponCode
      if (time) params.startTime = time[0] && time[0]
      if (time) params.endTime = time[0] && time[1]
      if (time) params.userId = userId
      const {
        data: { records, total }
      } = await this.$http.coupon.voucherApi.getDetailList({ params })
      this.dataSource = records
      this.total = total
    },
    // 导出
    async exportFile(key) {
      // 存在key则是导出全部
      if (!key) {
        if (!this.ids.length) return this.$message.error('请选择要导出的数据！')
      }
      const headerData = this.columns.filter(item => item.prop).map(item => item.label)
      headerData.splice(1, 0, '兑换人')
      headerData.splice(2, 0, '兑换人手机号')

      const filterData = this.columns.filter(item => item.prop).map(item => item.prop)
      filterData.splice(1, 0, 'nickName')
      filterData.splice(2, 0, 'mobile')

      const list = key
        ? this.$lodash.cloneDeep(await this.exportAllFile())
        : this.$lodash.cloneDeep(this.selectList)

      const tableData = list.map(item => {
        item.count = 'x1'
        item.integral = `+${item.integral}`
        item.exchange_way = '小程序扫码'
        item.nickName = item.baseUserInfo.nickName
        item.mobile = item.baseUserInfo.mobile
        item.storeName = item.storeName || '暂无'
        return item
      })
      export2Excel(headerData, tableData, filterData, '已兑换', () => {
        this.$message.success('导出成功！')
      })
    },
    // 导出全部
    async exportAllFile() {
      const params = {
        // 0: 未出库, 1: 未兑换, 2: 已兑换, 3: 作废
        couponId: this.id,
        status: 2,
        pageNo: 1,
        pageSize: this.total
      }
      const { couponCode, acquireRatio } = this.formOption
      if (couponCode) params.couponCode = couponCode
      if (acquireRatio) params.acquireRatio = acquireRatio
      const {
        data: { records }
      } = await this.$http.coupon.voucherApi.getDetailList({ params })
      return records
    },
    // 监听选择行数据
    selectChange(list) {
      this.selectList = list
    },
    // 搜索
    searchHandle() {
      this.listQuery.pageNo = 1
      this.getDetailList()
    }
  }
}
</script>

<style lang="scss" scoped></style>
